<template>
  <div class="home-container">
    <!-- Header -->
    <div class="header">
      <div class="header-content">
        <!-- 左侧logo区域 -->
        <el-col :span="12">
          <div class="left-area">
            <img src="@/assets/logo.png" alt="logo" class="logo">
            <div class="title-area">
              <h1>校园志愿服务系统</h1>
              <p>校园志愿服务网</p>
            </div>
          </div>
        </el-col>

        <!-- 右侧功能区域 -->
        <el-col :span="12">
          <div class="right-area">
            <div class="top-links">
              <a href="https://chinavolunteer.mca.gov.cn/site/home" class="top-link">中国志愿服务网</a>
              <el-button type="primary" @click="showFeedbackPanel = true" style="position: fixed; bottom: 20px; right: 20px; padding: 12px 24px; border-radius: 8px;">意见反馈</el-button>
              <template v-if="username">
                <span>欢迎, {{ username }}</span>
                <a @click="logout" style="cursor: pointer;">退出登录</a>
              </template>
              <template v-else>
                <a @click="showLoginDialog" style="cursor: pointer;">登录</a>
                <router-link to="/register" @click.prevent="() => handleRegisterType('volunteers')">志愿者注册</router-link>
                <router-link to="/register" @click.prevent="() => handleRegisterType('organizations')">志愿团队注册</router-link>
              </template>
            </div>

            <div class="search-bar">
              <img src="@/assets/logo2.png" alt="logo2" class="logo2">
            </div>

          </div>
        </el-col>
      </div>
    </div>

    <!-- 导航栏 -->
    <div class="nav-menu">
      <div class="menu-content">
        <el-menu mode="horizontal" :default-active="activeIndex" class="main-menu" router>
          <el-menu-item index="/home">首页</el-menu-item>
          <el-menu-item index="/volunteer-project">志愿项目</el-menu-item>
          <el-menu-item index="/volunteer-team">志愿队伍</el-menu-item>
          <el-menu-item index="/volunteer-elegance">志愿风采</el-menu-item>
          <el-menu-item index="/media-coverage">信息动态</el-menu-item>
          <el-menu-item index="/notices-and-announcements">媒体报道</el-menu-item>
          <template v-if="type === 'user'">
            <el-menu-item index="/personal-center">个人中心</el-menu-item>
          </template>
          <template v-else-if="type === 'organizations'">
            <el-menu-item index="/organization-center">组织中心</el-menu-item>
          </template>
          <template v-else-if="type === ''">
            <el-menu-item index="/personal-center">个人中心</el-menu-item>
          </template>
          <template v-else-if="type === 'admin'">
            <el-menu-item index="/personal-center">个人中心</el-menu-item>
          </template>
        </el-menu>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <slot></slot>

    <!-- 底部 -->
    <div class="footer">
      <div class="footer-content">
        <!-- 友情链接 -->
        <div class="friend-links">
          友情链接： 
          <a href="#">中国社会组织政务服务平台</a> | 
          <a href="#">中国社会工作网</a> | 
          <a href="#">中华志愿者协会</a>
        </div>

        <!-- 分隔线 -->
        <div class="divider"></div>

        <!-- 版权信息 -->
        <div class="copyright-info">
          <div>版权所有：桂林电子科技大学</div>
          <div>网站标识码：yy1234567890</div>
          <div>ICP备案编号：桂ICP备7777777号</div>
          <div class="info-row">
            <span>客服电话：8888888888</span>
            <span>推荐浏览器：谷歌浏览器（点击安装）</span>
            <a href="#" class="gov-link">
              <img src="@/assets/gov-icon.png" alt="政府网站找错" />
              政府网站找错
            </a>
          </div>
          <!-- 访问统计 -->
          <div class="visit-count">
            浏览网站人数统计：
            <span class="count-number">03441097</span>
          </div>
        </div>
      </div>
    </div>


    <!-- 登录弹出框 -->
    <el-dialog v-model="loginDialogVisible" title="请选择登录方式" width="500px" align-center style="font-weight: bold;">
      <div class="login-options">
        <div class="login-option" @click="handleLogin('volunteers')" style="cursor: pointer;">
          <el-icon class="option-icon"><User /></el-icon>
          <h3>志愿者登录</h3>
          <p>什么是志愿者</p>
          <p>有哪些权利和义务</p>
        </div>
        <div class="login-option" @click="handleLogin('organizations')" style="cursor: pointer;">
          <el-icon class="option-icon"><UserFilled /></el-icon>
          <h3>志愿队伍登录</h3>
          <p>管理项目</p>
        </div>
        <div class="login-option" @click="handleLogin('admin')" style="cursor: pointer;">
          <el-icon class="option-icon"><Lock /></el-icon>
          <h3>管理部门登录</h3>
          <p>管理部门登录</p>
        </div>
      </div>
    </el-dialog>
    <el-drawer v-model="showFeedbackPanel" title="意见反馈" direction="rtl" size="30%" :with-header="false" class="feedback-drawer" @open="fetchMessages">
      <div class="feedback-panel">
        <div class="feedback-header">
          <h2>意见反馈</h2>
          <p>欢迎提供您的宝贵意见，我们将尽快回复</p>
        </div>
        <div class="messages">
          <div v-for="(message, index) in messages" :key="index" 
               :class="['message', { 'response': message.isResponse }]">
            <div class="message-content">
              <span v-if="message.isResponse">{{ message.responder }}</span>
              <span v-else>{{ message.content }}</span>
            </div>
          </div>
          <div v-if="messages.length === 0" class="empty-state">
            <el-icon><ChatDotRound /></el-icon>
            <p>暂无消息，请开始您的反馈</p>
          </div>
        </div>
        <div class="input-container">
          <el-input 
            v-model="newMessage" 
            placeholder="请输入反馈内容" 
            @keyup.enter="sendMessage" 
            class="chat-input"
            :maxlength="200"
            :show-word-limit="true"
            type="textarea"
            :rows="2"
          >
          </el-input>
          <el-button type="primary" @click="sendMessage" class="send-button" :disabled="!newMessage.trim()">
            <el-icon><Position /></el-icon>
            发送
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { Search, User, UserFilled, Lock, Position, ChatDotRound } from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const loginDialogVisible = ref(false)
const searchCategory = ref('news')
const searchKeyword = ref('')
const activeIndex = ref(route.path)
const username = ref('')
const type = ref('')
const showFeedbackPanel = ref(false)
const messages = ref([])
const newMessage = ref('')

const showLoginDialog = () => {
  loginDialogVisible.value = true
}

const logout = () => {
  localStorage.clear()
  localStorage.removeItem('loginTable')
  username.value = null
  type.value = ''
  router.push('/login')
}

// 检查表单是否有内容
const checkFormContent = () => {
  const form = JSON.parse(localStorage.getItem('registerFormData') || '{}')
  return Object.values(form).some(value => value !== '')
}

// 处理注册类型选择
const handleRegisterType = async (type) => {
  console.log('handleRegisterType called with type:', type);
  // 如果当前在注册页面且有表单内容
  if (route.path === '/register' && checkFormContent()) {
    try {
      console.log('Showing confirmation dialog');
      await ElMessageBox.confirm(
        '当前页面信息未保存，切换将丢失已填写的信息，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      console.log('Confirmed, clearing form data and updating type');
      // 用户点击确定，清空表单并更新类型
      localStorage.removeItem('registerFormData')
      localStorage.setItem('loginTable', type)
      // 如果点击的是当前类型，刷新页面
      if (type === localStorage.getItem('loginTable')) {
        router.go(0)
      } else {
        // 如果是切换到其他类型，先回到首页再进入注册页
        await router.push('/home')
        router.push('/register')
      }
    } catch {
      console.log('User clicked cancel');
      // 用户点击取消，不做任何操作
      return
    }
  } else {
    // 没有表单内容，直接处理
    localStorage.setItem('loginTable', type)
    console.log('No form content, directly setting type and navigating');
    if (route.path === '/register') {
      if (type === localStorage.getItem('loginTable')) {
        router.go(0)
      } else {
        await router.push('/home')
        router.push('/register')
      }
    } else {
      router.push('/register')
    }
  }
}

const handleLogin = (type) => {
  const loginTable = type === 'zhiyuanzhe' ? 'volunteers' : 
                    type === 'zhiyuantuanti' ? 'organizations' : 
                    'admin'
  localStorage.setItem('loginTable', type)
  loginDialogVisible.value = false
  
  if (route.path === '/login') {
    // 如果已经在登录页面，先导航到首页再回到登录页面以触发刷新
    router.push('/home').then(() => {
      router.push('/login')
    })
  } else {
    // 不在登录页面，直接跳转
    router.push('/login')
  }
}

// Fetch existing feedback messages
const fetchMessages = async () => {
  try {
    const userId = localStorage.getItem('volunteerId')
    if (userId) {
      const response = await axios.get(`http://localhost:9090/questionAnswer/${userId}`)
      const newMessages = response.data.map(msg => ({
        id: msg.id,
        content: msg.answer,
        responder: msg.answeredBy,
        time: new Date(msg.createdAt).toLocaleTimeString('zh-CN', {hour: '2-digit', minute:'2-digit'}),
        isResponse: !!msg.answeredBy
      }))
      
      // Merge new messages with existing ones, avoiding duplicates
      const existingIds = new Set(messages.value.map(m => m.id))
      const uniqueNewMessages = newMessages.filter(msg => !existingIds.has(msg.id))
      messages.value = [...messages.value, ...uniqueNewMessages]
        .sort((a, b) => new Date(a.time) - new Date(b.time))
    }
  } catch (error) {
    console.error('Error fetching messages:', error)
  }
}

// Send new feedback message
const sendMessage = async () => {
  if (newMessage.value.trim()) {
    try {
      const messageData = {
        answer: newMessage.value,
        userId: localStorage.getItem('volunteerId') || null
      }
      
      const response = await axios.post('http://localhost:9090/questionAnswer', messageData)
      // Add the new message to the existing messages array
      messages.value.push({
        id: response.data.id,
        content: newMessage.value,
        time: new Date().toLocaleTimeString('zh-CN', {hour: '2-digit', minute:'2-digit'}),
        isResponse: false
      })
      newMessage.value = ''
    } catch (error) {
      console.error('Error sending message:', error)
    }
  }
}

onMounted(() => {
  username.value = localStorage.getItem('username') || ''
  type.value = localStorage.getItem('type') || ''
  fetchMessages()
})
</script>

<style>
@import '../assets/global.css';

.feedback-drawer {
  border-radius: 16px 0 0 16px;
  box-shadow: 0 0 24px rgba(0, 0, 0, 0.15);
  background: linear-gradient(145deg, #ffffff, #f8f9fa);
}

.feedback-panel {
  background: #ffebee;
  height: 100%;
  padding: 0;
  border-radius: 16px 0 0 16px;
  display: flex;
  flex-direction: column;
}

.feedback-header {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f2f5;
  background: linear-gradient(135deg, #d32f2f, #f44336);
  color: white;
  border-radius: 16px 0 0 0;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  scroll-behavior: smooth;
  background-color: #ffebee;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message {
  margin-bottom: 20px;
  animation: slideIn 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  align-self: flex-end;
  max-width: 85%;
  position: relative;
}

.message.response {
  align-self: flex-start;
}

.message-content {
  background: #2196f3;
  color: white;
  border-radius: 18px 18px 0 18px;
  padding: 12px 16px;
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.2);
  word-break: break-word;
  line-height: 1.5;
  position: relative;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-size: 14px;
}

.response .message-content {
  background: #4caf50;
  border-radius: 18px 18px 18px 0;
}

.message-content:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(33, 150, 243, 0.3);
}

.response .message-content:hover {
  box-shadow: 0 6px 16px rgba(76, 175, 80, 0.3);
}

.message-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  opacity: 0.8;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.responder {
  font-weight: 500;
  color: #4caf50;
}

.message-time {
  margin-left: 8px;
}

.input-container {
  padding: 16px 24px 24px;
  background: white;
  border-top: 1px solid #f0f2f5;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.chat-input {
  width: 100%;
  border-radius: 8px;
}

.chat-input :deep(.el-textarea__inner) {
  resize: none;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.chat-input :deep(.el-textarea__inner:focus) {
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.15);
}

.send-button {
  align-self: flex-end;
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 500;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.send-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.2);
}

.send-button .el-icon {
  font-size: 16px;
}

</style>